package com.ilikesoup.instant.logger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;
import java.util.Objects;
import java.util.function.Function;

public class Monitor {

    private static final Logger logger = LoggerFactory.getLogger(Monitor.class);
    /**
     * 属性变化监听器组件
     */
    protected PropertyChangeSupport propertyChangeSupport;

    protected Monitor parent;

    protected String propPrefix;

    protected Function<Object, String> toStrFunc;

    Monitor(){}

    protected void firePropertyChange(PropertyChangeEvent changeEvent) {
        firePropertyChange(propertyChangeSupport, changeEvent);
    }

    private void firePropertyChange(PropertyChangeSupport propertyChangeSupport, PropertyChangeEvent changeEvent) {
        if (changeEvent != null) {
            if (parent != null && !Objects.equals(changeEvent.getPropagationId(), System.identityHashCode(parent))) {
                parent.firePropertyChange(createPropagateEvent(changeEvent, parent.propPrefix));
                return;
            }
            if (propertyChangeSupport != null) {
                propertyChangeSupport.firePropertyChange(changeEvent);
            }
        }
    }

    private PropertyChangeEvent createPropagateEvent(PropertyChangeEvent changeEvent, String propPrefix) {
        PropertyChangeEvent newEvent = new PropertyChangeEvent(
                changeEvent.getSource(), propPrefix + changeEvent.getPropertyName(), changeEvent.getOldValue(), changeEvent.getNewValue());
        newEvent.setPropagationId(changeEvent.getPropagationId());
        return newEvent;
    }

}
